<template>
  <div class="mt-1">
    <van-form>
      <!--       <h4 style="margin: 0 0 0.2rem 1rem; color: gray">
        当前产区:{{ this.$store.getters.productionLine }}
      </h4> -->
      <h5 class="titlestyle">
        <span style="margin: 0 0 0 0.3rem"
          >当前产区:{{ this.$store.getters.productionLine }}
        </span>
        <!--  <span style="margin: 0 0 0 1rem">
          当前生产班次:{{ this.backData.WorkTeam
          }}{{ this.backData.WorkShift }}</span
        >
        <span style="margin: 0 0 0 3rem">段:{{ this.backData.WorkNo }}</span> -->
      </h5>
      <van-field
        readonly
        clickable
        :value="processids"
        label="工单号"
        placeholder="请选择工单号"
        @click="processOrderVisible = true"
      />
      <van-popup
        v-model="processOrderVisible"
        position="bottom"
        style="height: 100%"
        class="bg-default"
      >
        <process-order-repeat @get-val="getProcessOrder" @back="back" />
      </van-popup>
      <!-- 选择框 -->
      <!--  <van-checkbox-group v-model="IsChange">
        <van-cell-group>
          <van-cell
            clickable
            :key="item"
            :title="`换产前最终投产`"
            @click="toggle()"
          >
            <van-checkbox name="1" ref="checkboxes" />
          </van-cell>
        </van-cell-group>
      </van-checkbox-group> -->
      <van-cell clickable :title="`换产前最终投产`" @click="toggle()">
        <van-checkbox v-model="IsChange" />
      </van-cell>
      <!-- <van-field
        readonly
        clickable
        :value="productorder"
        label="物料SKU"
        placeholder="点击选择"
        @click="SKUPicker = true"
      />
      <van-popup v-model="SKUPicker" position="bottom">
        <van-picker
          show-toolbar
          :columns="columns"
          @confirm="SKUAdjustConfirm"
          @cancel="SKUPicker = false"
        />
      </van-popup> -->
      <van-field
        v-model="code"
        clearable
        ref="pmfocus"
        @focus="stopKeyborad"
        label="返工拍码"
        placeholder="请输入返工拍码"
      />
      <!-- 弹出框 ,初改-->
      <van-dialog
        v-model="visible"
        show-cancel-button
        :beforeClose="handleSure"
        confirm-button-color="rgba(25, 137, 250,1)"
      >
        <div class="ip-container">
          <van-field
            label="物料号"
            :value="this.bucketData.ProductId"
            readonly
          />
          <van-field
            label="物料名称"
            :value="this.bucketData.ProductName"
            readonly
          />
          <van-field
            label="桶拍号"
            :value="this.bucketData.BucketCode"
            readonly
          />
          <van-field
            label="玛氏批次"
            :value="this.bucketData.AtlasBatch"
            readonly
          />
          <van-field
            label="入库时间"
            :value="this.bucketData.OperatedOn"
            readonly
          />
          <van-field label="消耗数量" required v-model="newNum" />
        </div>
      </van-dialog>
      <ag-grid-vue
        style="width: 100%; height: 55vh"
        class="ag-theme-alpine mt-1"
        :columnDefs="columnDefs"
        :defaultColDef="defaultColDef"
        :gridOptions="gridOptions"
        :singleClickEdit="true"
        rowSelection="multiple"
        :rowData="rowData"
      >
      </ag-grid-vue>
      <audio src="../../assets/warning.mp3" preload="auto" id="bgMusic"></audio>
    </van-form>
  </div>
</template>

<script>
import { Dialog } from "vant";
import { Picker } from "vant";
import { AgGridVue } from "ag-grid-vue";
import { AgGrid } from "../../mixins/AgGrid";
import { parseQRCode, toast } from "../../utils/common";
import {
  checkbucketDeatil,
  workAgainSubmit,
  GetOutStorege,
  GetReworkMaterials,
} from "../../api/feeding";
import ProcessOrderRepeat from "../../components/ProcessOrderRepeat.vue";
//import { getReWorkSearchList } from "../../api/return";

export default {
  name: "WIP",
  components: {
    AgGridVue,
    [Dialog.Component.name]: Dialog.Component,
    [Picker.name]: Picker,
    ProcessOrderRepeat,
  },
  mixins: [AgGrid],
  data() {
    return {
      code: "",
      savenum: "",
      visible: false,
      newNum: "",
      OldNum: "",
      IsChange: "",
      processids: "",
      //processOrder: [],
      processOrderVisible: false,
      columnDefs: [
        { headerName: "物料号", field: "ProductId", width: 90 },
        { headerName: "物料名称", field: "ProductName", width: 125 },
        { headerName: "生产日期", field: "ProductionDate", width: 100 },
        { headerName: "数量", field: "Num", width: 70 },
      ],
      rowData: [],
      //backData: {},
      bucketData: [],
      reworkData: [],
      // processOrderData: [],
      Ordermaterial: "",
      //columns: [],
    };
  },
  watch: {
    code(val) {
      if (val.length > 9) {
        if (val) {
          console.log(val);
          this.newNum = "";
          let res = parseQRCode(val);
          this.productorder = res.materialCode;
          if (this.reworkData.indexOf(this.productorder) != -1) {
            this.checkbucketDeatil(res.palletNo);
          } else {
            toast("返工号内无此拍码");
          }
        }
      } else if (val.length != 0) {
        this.playMusic();
        toast("此拍格式不对");
      }
      this.code = "";
      this.$refs.pmfocus.focus();
    },
  },
  methods: {
    // 消除获取焦点时自动弹出键盘
    stopKeyborad() {
      this.$refs.pmfocus.$refs.input.setAttribute("readonly", "readonly");
      setTimeout(() => {
        this.$refs.pmfocus.$refs.input.removeAttribute("readonly");
      }, 200);
    },
    //播放警示音
    playMusic() {
      setTimeout(() => {
        let audio = document.getElementById("bgMusic");
        audio.play();
      }, 200);
    },
    //获取选中的工单号和物料号
    getProcessOrder(val) {
      let processOrderProdoter = [],
        processOrderMaterial = [];
      /* _this = this;
      this.processOrderData = []; */
      val.map((it) => {
        processOrderProdoter.push(it.PROCORDER);
        processOrderMaterial.push(it.MATERIAL);
        /*  _this.processOrderData.push({
          PROCORDER: it.PROCORDER,
          MATERIAL: it.MATERIAL,
        }); */
      });
      this.processids = processOrderProdoter.join(",");
      this.Ordermaterial = processOrderMaterial.join(",");
      this.processOrderVisible = false;
      this.getReworkMaterials(processOrderMaterial.join(","));
      this.$refs.pmfocus.focus();
    },
    back() {
      //返回
      this.processOrderVisible = false;
    },
    //复选框选择
    toggle() {
      if (this.IsChange == false) {
        this.IsChange = true;
      } else {
        this.IsChange = false;
      }
      //this.$refs.checkboxes.toggle();
      this.$refs.pmfocus.focus();
      console.log(this.IsChange, Number(this.IsChange));
    },
    //获取ischange
    async getOutStorege() {
      let res = await GetOutStorege(this.$store.getters.productionLine);
      console.log(res);
      if (res.Status == 200) {
        if (res.Data) {
          if (res.Data.Rer05 == 0) {
            this.IsChange = false;
            console.log(this.IsChange);
            this.processids = res.Data.Rer03;
            this.getReworkMaterials(res.Data.Rer04);
          } else {
            this.IsChange = false;
          }
        }
      } else {
        toast(res.Msg);
      }
    },
    //查找返工号
    async getReworkMaterials(materials) {
      let _this = this;
      let res = await GetReworkMaterials(materials);
      this.reworkData = [];
      if (res.Status == 200) {
        if (res.Data.length != 0) {
          console.log(res.Data);
          res.Data.map((it) => {
            _this.reworkData.push(it.F_ItemName);
          });
        } else {
          toast("未查询到相关返工号");
        }
      } else {
        toast(res.Msg);
      }
      console.log(res);
    },
    //取消/确认键
    handleSure(action, done) {
      if (action === "confirm") {
        if (parseFloat(this.newNum) <= parseFloat(this.OldNum)) {
          console.log(this.newNum);
          this.findPat();
          done();
          this.$refs.pmfocus.focus();
        } else {
          this.playMusic();
          toast("已超出桶量");
          this.newNum = "";
          done(false);
        }
      } else {
        done();
        this.$refs.pmfocus.focus();
      }
    },
    //检查桶是否可以投料
    async checkbucketDeatil(id) {
      if (id != "") {
        this.Code = id;
      }
      console.log(this.Code);
      //checkbucketDeatil = (line, material, bucketno)
      let res = await checkbucketDeatil(
        this.$store.getters.productionLine,
        this.productorder,
        //this.backData.ProductId,
        id
      );
      if (res.Status == 200 && res.Data) {
        console.log(res);
        this.bucketData = res.Data;
        this.OldNum = res.Data.StockQuantity;
        this.newNum = res.Data.StockQuantity; //StockQuantity
        console.log(this.OldNum, this.newNum);
        this.visible = true;
      } else {
        if (res.Status == 201 && res.Data) {
          console.log(res);
          this.playMusic();
          //Dialog({ message: res.Msg });
          Dialog.confirm({
            title: "提示",
            message: res.Msg,
          })
            .then(() => {
              console.log("1");
              this.bucketData = res.Data;
              this.OldNum = res.Data.StockQuantity;
              this.newNum = res.Data.StockQuantity;
              console.log(this.OldNum, this.newNum);
              this.visible = true;
            })
            .catch(() => {
              this.$refs.pmfocus.focus();
            });
        } else {
          this.playMusic();
          toast(res.Msg);
          console.log(res);
        }
      }
    },
    //从外界添加数据
    async findPat() {
      let _this = this;
      console.log(this.Code);
      /*     this.processOrderData.find(it=>{
        
      }) */
      let res = await workAgainSubmit(
        this.$store.getters.user,
        this.$store.getters.productionLine,
        this.productorder,
        this.Code,
        this.newNum,
        this.processids,
        Number(this.IsChange),
        this.Ordermaterial
      );
      console.log(res);
      if (res.Status == 200 && res.Data) {
        this.rowData.push({
          ProductName: res.Data.ProductName,
          ProductId: res.Data.ProductId,
          Num: _this.newNum,
          ProductionDate: res.Data.ProductStartTime,
          BucketCode: _this.Code,
        });
      } else {
        this.playMusic();
        toast(res.Msg);
      }
    },
  },
  mounted() {
    //this.getReWorkList();
    this.getOutStorege();
    this.$refs.pmfocus.focus();
  },
};
</script>
<style scoped>
.titlestyle {
  color: gray;
  margin-top: 0.1rem;
  margin-bottom: 0.5rem;
}
</style>
